package org.apache.sad.core.framework.utils;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import weblogic.jms.extensions.WLMessageProducer;

public class AppUtil {

	private static final Logger logger = Logger.getLogger(AppUtil.class);

	public static Properties getProps(String propDir, String propFile){
		//loading props from system properties 
		FileReader f =null;
		Properties props = new Properties();
		try {
			String dir = System.getProperty(propDir);
			if(dir != null && !dir.endsWith("/") && !dir.endsWith("\\"))
				dir = dir + File.separator;
			f = new FileReader(dir + propFile);
			props.load(f);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(f!=null)
				try {
					f.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return props;
	}

	public static void configureLoging(String logDir, String seperator, String logPropFileName){
		Properties props = new Properties();
		InputStream in = null;
		try {
			logger.info(" ################################ " + System.getProperty(logDir));

			in = new FileInputStream(System.getProperty(logDir)+seperator+logPropFileName);
			//Thread.currentThread().getContextClassLoader().getResourceAsStream("/opt/neps/config/log4j.properties");
			props.load(in);
			PropertyConfigurator.configure(props);
		} catch (Exception e) {
			logger.error("Could not create JNDI API context: " + e);
			e.printStackTrace();
		}
		finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}

	}


	// Used from AQForwarding AQ-JMS Bridge
	public static InitialContext getInitialContext(Properties props, String initialContextFactory, String providerURL, String username, String userpwd)   {
		InitialContext context = null;
		Hashtable<String,String> env = new Hashtable<String,String>();
		try {
			if(initialContextFactory != null && initialContextFactory.length() != 0)
				env.put(Context.INITIAL_CONTEXT_FACTORY, props.getProperty(initialContextFactory));
			if(providerURL != null && providerURL.length() != 0)
				env.put(Context.PROVIDER_URL, props.getProperty(providerURL));
			if(username != null && username.length() != 0)
				env.put(Context.SECURITY_PRINCIPAL, props.getProperty(username));
			if(userpwd != null && userpwd.length() != 0)
				env.put(Context.SECURITY_CREDENTIALS, props.getProperty(userpwd));
			context = new InitialContext(env);
		} catch (NamingException ne) {
			ne.printStackTrace();
		}

		return context;
	}
	
	//Used from AQForwarding AQ-JMS Bridge
	public static void forwardingMessage(Message msg, String uoo, Context ctx, Properties props, String connectFact, String outboundDest, String uOfOrd){

		ConnectionFactory cf = null;
		Destination dest = null;
		Connection conn = null;
		Session session = null;
		String destination = "";

		try {
			cf = (ConnectionFactory) ctx.lookup(props.getProperty(connectFact));
			conn = cf.createConnection();
			conn.start();
			session = conn.createSession(false,Session.AUTO_ACKNOWLEDGE);
			destination = props.getProperty(outboundDest);

			if(destination!= null) {
				dest = (Destination) ctx.lookup(destination);
				MessageProducer producer = session.createProducer(dest);
				((WLMessageProducer) producer).setUnitOfOrder(uoo);

				logger.info(uOfOrd + ((WLMessageProducer) producer).getUnitOfOrder());		

				producer.send(msg);
				producer.close();

				//				if(destination.contains("Topic")) {
				//					dest = (Destination) ctx.lookup(destination);
				//					producer = session.createProducer(dest);
				//					pub.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
				//					pub.send(msg);
				//				    pub.close();
				//				    logger.info("sent.");
				//				} else if(destination.contains("Queue")){
				//					dest = (Destination) ctx.lookup(destination);
				//					queueSender = session.create(topic);
				//					pub.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
				//					pub.send(msg);
				//				    pub.close();
				//				    logger.info("sent.");
				//				}
			} else {
				logger.debug("No Destination found.");
			}

		} catch (JMSException e) {
			logger.error(" AppUtil.JMSException: "+ e);
			e.printStackTrace();
		} catch (Exception e) {
			logger.error(" AppUtil.Exception: " +e);
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (JMSException e) {
					logger.error("AppUtil.Exception: " +e);
					e.printStackTrace();
				}
			}

		}
	}
}